package edu.gu.hajo.gcl.parser;

import edu.gu.hajo.gcl.exception.ParseException;
import edu.gu.hajo.gcl.script.Script;

/**
 * Parse anything [...]   (except if in {...})
 * 
 * @author hajo
 */
public final class CmdSubstParser /*implements IParser*/ {

	public String parse(Script script ) {
		
		Parser.parseSpace(script);
		
		StringBuffer buffer = new StringBuffer();
		int bracesLevel = 0;

		script.next(); // Skip [
		
		int nestLevel = 1;
		char ch;
		while ((ch = script.next()) != 0){
			switch (ch) {
			case '[':
				if (bracesLevel == 0) {
					nestLevel++;
				}
				buffer.append(ch); 
				break;
			case ']':
				if( bracesLevel == 0){
					nestLevel--;
					if (nestLevel == 0 ) { // Tricky!!
						return buffer.toString(); 
					}
				}
				buffer.append(ch);
				break;
			case '{':
				bracesLevel++;
				buffer.append(ch);
				break;
			case '}':
				if (bracesLevel > 0) {
					bracesLevel--;
				}
				buffer.append(ch);
				break;
			default:
				buffer.append(ch);
			}
		}
		throw new ParseException(script.getPos() + ": Missing ]");
	}
}
